package com.iwhalecloud.bss.kite.cucc.service.cust;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.common.util.SeqUtils;
import com.iwhalecloud.bss.kite.common.util.TransactionUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.cust.ILatestCustomerService;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.LatestEntertainCustomerDTO;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.LatestEntertainCustomerCache;
import com.iwhalecloud.bss.kite.cucc.dataservice.entity.LatestEntertainCustomer;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.cust.LatestEntertainCustomerMapper;
import com.iwhalecloud.bss.kite.cucc.service.inst.ProdInstService;
import tk.mybatis.mapper.entity.Example;

/**
 * @Description: TODO
 *
 * @author lyx
 * @date 2020年11月17日
 * @version V1.0
 * @Package com.iwhalecloud.bss.kite.cucc.service.cust
 */
@Service
public class LatestCustomerService implements ILatestCustomerService {

    private static final ZLogger LOGGER = ZLoggerFactory.getLogger(LatestCustomerService.class, KeyConsts.LOG_MODULE);

    @Autowired
    private LatestEntertainCustomerMapper latestCustMapper;
    @Autowired
    private ProdInstService prodInstService;

    @Override
    public List<LatestEntertainCustomerDTO> listLatestCustomer(String staffId, String eparchyCode) {
        LOGGER.info("listLatestCustomer==" + staffId +"  " + eparchyCode);
        return KiteBeanUtils.copyPropsForList(
            LatestEntertainCustomerCache.get(KiteStringUtils.join(staffId, SymbolConsts.UNDERLINE, eparchyCode)),
            LatestEntertainCustomerDTO.class);
    }

    @Override
    public void dealLatestCustomer(String staffId, String orgId, String lanId, CuccContextCustDTO custDto) {
        // 先判断该工号下有没有受理该客户的记录，如果没有则新增记录，如果有则更新记录修改时间
        Example example = new Example(LatestEntertainCustomer.class);
//        example.createCriteria().andEqualTo("custId", custDto.getCustId()).andEqualTo("updateStaff", staffId).andEqualTo("lanId", custDto.getEparchyCode());
        // update by ma.junjun 2021-11-13 集团工号或者云工号进入，lanId和归属地市不一致，导致数据库重复插入，修改为使用lanId，和插入保持一致。
          example.createCriteria().andEqualTo("custId", custDto.getCustId()).andEqualTo("updateStaff", staffId).andEqualTo("lanId", KiteStringUtils.isEmpty(lanId)?custDto.getEparchyCode():lanId);

        LatestEntertainCustomer latestCust = latestCustMapper.selectOneByExample(example);
        if (Objects.nonNull(latestCust)) {
            latestCust.setUpdateDate(LocalDateTime.now());
            // add by ma.junjun 2021-09-17 客户中心客户状态变更，销售侧最近客户未更新问题，同时需要刷缓存 LatestEntertainCustomerCache
            latestCust.setCustState(custDto.getCustState());
            TransactionUtils.executeNew(() -> latestCustMapper.updateByPrimaryKeySelective(latestCust));
        }
        else {
            LatestEntertainCustomer latestCustNew = new LatestEntertainCustomer();
            latestCustNew.setEntertainId(Long.valueOf(SeqUtils.getNext("SEQ_LATEST_ENTERTAIN_CUSTOMER")));
            latestCustNew.setCustId(Long.valueOf(custDto.getCustId()));
            latestCustNew.setCustName(custDto.getCustName());
            latestCustNew.setGroupCustCode(custDto.getGroupId());
            latestCustNew.setCbssCustCode(Optional.ofNullable(custDto.getCbssId()).orElse(custDto.getCustId()));
            latestCustNew.setProvinceId(custDto.getProvinceCode());
            latestCustNew.setLanId(lanId);
            latestCustNew.setCertiType(custDto.getCertType());
            latestCustNew.setCertiNum(custDto.getCertiCode());
            latestCustNew.setCreditCode(custDto.getOrgCode());
            latestCustNew.setStatusCd("1000");
            latestCustNew.setStatusDate(LocalDateTime.now());
            latestCustNew.setCreateStaff(Long.valueOf(staffId));
            latestCustNew.setCreateDate(LocalDateTime.now());
            //latestCustNew.setCreatePost(Long.valueOf(Optional.ofNullable(custDto.getPostCode()).orElse("0")));
            latestCustNew.setCreateOrgId(Long.valueOf(orgId));
            latestCustNew.setUpdateStaff(Long.valueOf(staffId));
            latestCustNew.setUpdateDate(LocalDateTime.now());
            latestCustNew.setUpdateOrgId(Long.valueOf(orgId));
            latestCustNew.setCustState(custDto.getCustState());
            latestCustNew.setBbssCustId(custDto.getBbssCustId());
            TransactionUtils.executeNew(() -> latestCustMapper.insert(latestCustNew));
        }
        LatestEntertainCustomerCache.getInst().defaultReloadObject(KiteStringUtils.join(staffId, SymbolConsts.UNDERLINE, lanId));
    }

    @Override
    public List<LatestEntertainCustomerDTO> listLatestCustomerCloud(String staffId, String eparchyCode) {
        List<LatestEntertainCustomer> customerLists = LatestEntertainCustomerCache.get(KiteStringUtils.join(staffId, SymbolConsts.UNDERLINE, eparchyCode));
//        Iterator<LatestEntertainCustomer> iterator = customerLists.iterator();
//        while (iterator.hasNext()) {
//            LatestEntertainCustomer customerList = iterator.next();
//            Map<String, String> paramMap = new HashMap<>();
//            paramMap.put("custId", String.valueOf(customerList.getCustId()));
//            paramMap.put("provinceCode", customerList.getProvinceId());
//            paramMap.put("eparchyCode", customerList.getLanId());
//            paramMap.put("pageNum", "1");
//            paramMap.put("pageSize", "10");
//            UserQueryDTO userQueryDTO = prodInstService.listCloudProdInst(paramMap);
//            if (KiteListUtils.isEmpty(userQueryDTO.getUserList().getList())) {
//                iterator.remove();
//            }
//        }
        return KiteBeanUtils.copyPropsForList(customerLists, LatestEntertainCustomerDTO.class);
    }
}
